<template>
  <div class="public-lesson-plans">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h1 class="page-title">
            <el-icon><Reading /></el-icon>
            公开教案
          </h1>
          <p class="page-description">发现和学习其他教师分享的优质教案</p>
        </div>
        <div class="header-stats">
          <el-statistic title="总教案数" :value="totalCount" />
        </div>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-card class="search-card" shadow="never">
        <div class="search-controls">
          <!-- 搜索框 -->
          <div class="search-input">
            <el-input
              v-model="searchForm.q"
              placeholder="输入关键词搜索教案..."
              clearable
              @keyup.enter="handleSearch"
              @clear="handleClear"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
              <template #append>
                <el-button @click="handleSearch" :loading="loading">
                  搜索
                </el-button>
              </template>
            </el-input>
          </div>
          
          <!-- 筛选条件 -->
          <div class="filter-controls">
            <el-select
              v-model="searchForm.subject"
              placeholder="学科分类"
              clearable
              style="width: 120px"
              @change="handleSearch"
            >
              <el-option
                v-for="subject in subjectOptions"
                :key="subject._id"
                :label="subject.name"
                :value="subject.name"
              />
            </el-select>
            
            <el-select
              v-model="searchForm.grade"
              placeholder="适用年级"
              clearable
              style="width: 120px"
              @change="handleSearch"
            >
              <el-option
                v-for="grade in gradeOptions"
                :key="grade._id"
                :label="grade.name"
                :value="grade.name"
              />
            </el-select>
            
            <el-select
              v-model="searchForm.courseType"
              placeholder="课程类型"
              clearable
              style="width: 120px"
              @change="handleSearch"
            >
              <el-option
                v-for="courseType in courseTypeOptions"
                :key="courseType._id"
                :label="courseType.name"
                :value="courseType.name"
              />
            </el-select>
            
            <el-select
              v-model="searchForm.sortBy"
              style="width: 120px"
              @change="handleSearch"
            >
              <el-option label="最新发布" value="date" />
              <el-option label="最多浏览" value="views" />
              <el-option label="最多点赞" value="likes" />
              <el-option label="相关度" value="relevance" />
            </el-select>
          </div>
        </div>
        
        <!-- 热门标签 -->
        <div class="hot-tags" v-if="hotTags.length > 0">
          <span class="tags-label">热门标签：</span>
          <el-tag
            v-for="tag in hotTags"
            :key="tag"
            @click="handleTagSearch(tag)"
            class="hot-tag"
          >
            {{ tag }}
          </el-tag>
        </div>
      </el-card>
    </div>

    <!-- 教案列表 -->
    <div class="lesson-list-section">
      <el-card shadow="never" class="list-card">
        <!-- 列表头部 -->
        <div class="list-header">
          <div class="result-info">
            <span v-if="searchForm.q" class="search-keyword">
              搜索："{{ searchForm.q }}"
            </span>
            <span class="result-count">
              共找到 {{ totalCount }} 个教案
            </span>
          </div>
          
          <!-- 视图切换 -->
          <div class="view-controls">
            <el-button-group>
              <el-button
                :type="viewMode === 'grid' ? 'primary' : ''"
                @click="viewMode = 'grid'"
                :icon="Grid"
              />
              <el-button
                :type="viewMode === 'list' ? 'primary' : ''"
                @click="viewMode = 'list'"
                :icon="List"
              />
            </el-button-group>
          </div>
        </div>

        <!-- 教案网格视图 -->
        <div v-if="viewMode === 'grid'" class="lesson-grid" v-loading="loading">
          <div
            v-for="lesson in lessonPlans"
            :key="lesson._id"
            class="lesson-card"
            @click="handleViewLesson(lesson._id)"
          >
            <div class="lesson-card-header">
              <h3 class="lesson-title">{{ lesson.title }}</h3>
              <el-tag :type="getStatusType(lesson.status)" size="small">
                {{ getStatusText(lesson.status) }}
              </el-tag>
            </div>
            
            <div class="lesson-meta">
              <div class="meta-info">
                <el-tag size="small">{{ lesson.subject }}</el-tag>
                <el-tag size="small" type="success">{{ lesson.grade }}</el-tag>
                <el-tag size="small" type="warning">{{ lesson.courseType }}</el-tag>
              </div>
              
              <div class="lesson-stats">
                <span class="stat-item">
                  <el-icon><View /></el-icon>
                  {{ lesson.views || 0 }}
                </span>
                <span class="stat-item">
                  <el-icon><Star /></el-icon>
                  {{ lesson.likes || 0 }}
                </span>
              </div>
            </div>
            
            <div class="lesson-content">
              <p class="content-preview">{{ getContentPreview(lesson.content) }}</p>
            </div>
            
            <div class="lesson-author">
              <div class="author-info" v-if="lesson.author">
                <el-avatar :size="24" :src="getAuthorAvatarUrl(lesson.author.avatar)">
                  {{ lesson.author.name?.charAt(0) || '?' }}
                </el-avatar>
                <span class="author-name">{{ lesson.author.name || '匿名用户' }}</span>
              </div>
              <div class="author-info" v-else>
                <el-avatar :size="24">?</el-avatar>
                <span class="author-name">匿名用户</span>
              </div>
              <span class="publish-date">{{ formatDate(lesson.updatedAt) }}</span>
            </div>
            
            <!-- 标签 -->
            <div class="lesson-tags" v-if="lesson.tags && lesson.tags.length > 0">
              <el-tag
                v-for="tag in lesson.tags.slice(0, 3)"
                :key="tag"
                size="small"
                class="lesson-tag"
                @click.stop="handleTagSearch(tag)"
              >
                {{ tag }}
              </el-tag>
              <span v-if="lesson.tags.length > 3" class="more-tags">
                +{{ lesson.tags.length - 3 }}
              </span>
            </div>
          </div>
        </div>

        <!-- 教案列表视图 -->
        <div v-else class="lesson-list" v-loading="loading">
          <div
            v-for="lesson in lessonPlans"
            :key="lesson._id"
            class="lesson-item"
            @click="handleViewLesson(lesson._id)"
          >
            <div class="lesson-item-content">
              <div class="lesson-item-header">
                <h3 class="lesson-title">{{ lesson.title }}</h3>
                <div class="lesson-stats">
                  <span class="stat-item">
                    <el-icon><View /></el-icon>
                    {{ lesson.views || 0 }}
                  </span>
                  <span class="stat-item">
                    <el-icon><Star /></el-icon>
                    {{ lesson.likes || 0 }}
                  </span>
                </div>
              </div>
              
              <p class="lesson-description">{{ getContentPreview(lesson.content) }}</p>
              
              <div class="lesson-item-footer">
                <div class="lesson-meta">
                  <el-tag size="small">{{ lesson.subject }}</el-tag>
                  <el-tag size="small" type="success">{{ lesson.grade }}</el-tag>
                  <el-tag size="small" type="warning">{{ lesson.courseType }}</el-tag>
                </div>
                
                <div class="author-date">
                  <span class="author-name">{{ lesson.author?.name || '匿名用户' }}</span>
                  <span class="publish-date">{{ formatDate(lesson.updatedAt) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <el-empty
          v-if="!loading && lessonPlans.length === 0"
          description="暂无公开教案"
        >
          <el-button type="primary" @click="$router.push('/lesson-plans/create')">
            创建第一个教案
          </el-button>
        </el-empty>

        <!-- 分页 -->
        <div class="pagination-container" v-if="totalCount > 0">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="totalCount"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Reading,
  Search,
  View,
  Star,
  Grid,
  List
} from '@element-plus/icons-vue'
import { lessonPlanApi, type LessonPlan } from '@/api/lessonPlan'
import { categoryApi, type Category } from '@/api/category'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const lessonPlans = ref<LessonPlan[]>([])
const totalCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const viewMode = ref<'grid' | 'list'>('grid')

// 搜索表单
const searchForm = reactive({
  q: '',
  subject: '',
  grade: '',
  courseType: '',
  sortBy: 'date'
})

// 分类选项
const subjectOptions = ref<Category[]>([])
const gradeOptions = ref<Category[]>([])
const courseTypeOptions = ref<Category[]>([])
const hotTags = ref<string[]>(['教学设计', '课件', '教学反思', '作业设计', '评价方案'])

// 状态相关方法
const getStatusType = (status: string) => {
  const map: Record<string, string> = {
    draft: 'info',
    published: 'success',
    archived: 'warning'
  }
  return map[status] || 'info'
}

const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    draft: '草稿',
    published: '已发布',
    archived: '已归档'
  }
  return map[status] || status
}

// 获取内容预览
const getContentPreview = (content: string) => {
  // 移除HTML标签并截取前100个字符
  const plainText = content.replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim()
  return plainText.length > 100 ? plainText.slice(0, 100) + '...' : plainText
}

// 获取作者头像URL
const getAuthorAvatarUrl = (avatar?: string) => {
  if (!avatar) return ''
  
  // 如果已经是完整URL，直接返回
  if (avatar.startsWith('http')) {
    return avatar
  }
  
  // 开发环境下使用代理，直接返回相对路径
  // 生产环境需要配置 VITE_API_BASE_URL
  return avatar
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric'
  })
}

// 加载分类数据
const loadCategories = async () => {
  try {
    const { data } = await categoryApi.getAll()
    if (data && data.grouped) {
      subjectOptions.value = data.grouped.subject || []
      gradeOptions.value = data.grouped.grade || []
      courseTypeOptions.value = data.grouped.courseType || []
    }
  } catch (error: any) {
    console.error('加载分类失败:', error)
  }
}

// 加载公开教案列表
const loadLessonPlans = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      // 不需要显式传递status，后端会自动过滤为published
      ...searchForm
    }
    
    let response
    if (searchForm.q || searchForm.subject || searchForm.grade || searchForm.courseType) {
      // 使用搜索API
      response = await lessonPlanApi.search(params)
    } else {
      // 使用列表API - getList默认获取公开教案
      response = await lessonPlanApi.getList(params)
    }
    
    lessonPlans.value = response.data.lessonPlans
    totalCount.value = response.data.pagination.total
  } catch (error: any) {
    console.error('加载教案失败:', error)
    ElMessage.error(error.message || '加载教案失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  loadLessonPlans()
}

const handleClear = () => {
  searchForm.q = ''
  handleSearch()
}

const handleTagSearch = (tag: string) => {
  searchForm.q = tag
  handleSearch()
}

// 分页处理
const handlePageChange = (page: number) => {
  currentPage.value = page
  loadLessonPlans()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadLessonPlans()
}

// 查看教案详情
const handleViewLesson = (id: string) => {
  router.push(`/lesson-plans/${id}`)
}

// 页面初始化
onMounted(async () => {
  await loadCategories()
  await loadLessonPlans()
})
</script>

<style scoped>
.public-lesson-plans {
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 页面头部 */
.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 40px 0;
  margin-bottom: 24px;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 700;
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-description {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
}

.header-stats {
  text-align: right;
}

.header-stats :deep(.el-statistic__content) {
  color: white;
}

.header-stats :deep(.el-statistic__head) {
  color: rgba(255, 255, 255, 0.8);
}

/* 搜索区域 */
.search-section {
  max-width: 1200px;
  margin: 0 auto 24px auto;
  padding: 0 24px;
}

.search-card {
  border-radius: 12px;
}

.search-controls {
  display: flex;
  gap: 16px;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.search-input {
  flex: 1;
  min-width: 300px;
}

.filter-controls {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.hot-tags {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.tags-label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}

.hot-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.hot-tag:hover {
  transform: scale(1.05);
}

/* 列表区域 */
.lesson-list-section {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
}

.list-card {
  border-radius: 12px;
  min-height: 600px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.result-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-keyword {
  font-weight: 600;
  color: #409eff;
}

.result-count {
  color: #666;
  font-size: 14px;
}

/* 网格视图 */
.lesson-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.lesson-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #f0f0f0;
}

.lesson-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.lesson-card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.lesson-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  flex: 1;
  margin-right: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.lesson-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.meta-info {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.lesson-stats {
  display: flex;
  gap: 12px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #666;
  font-size: 12px;
}

.lesson-content {
  margin-bottom: 16px;
}

.content-preview {
  margin: 0;
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.lesson-author {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.author-name {
  font-size: 14px;
  color: #606266;
}

.publish-date {
  font-size: 12px;
  color: #909399;
}

.lesson-tags {
  display: flex;
  align-items: center;
  gap: 6px;
}

.lesson-tag {
  cursor: pointer;
}

.more-tags {
  font-size: 12px;
  color: #909399;
}

/* 列表视图 */
.lesson-list {
  margin-bottom: 24px;
}

.lesson-item {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #f0f0f0;
}

.lesson-item:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  transform: translateY(-1px);
}

.lesson-item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.lesson-description {
  margin: 0 0 16px 0;
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
}

.lesson-item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.author-date {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #666;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding-top: 24px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .search-controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input {
    min-width: auto;
  }
  
  .filter-controls {
    justify-content: space-between;
  }
  
  .lesson-grid {
    grid-template-columns: 1fr;
  }
  
  .list-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>